package com.heima.behavior.advice;

import com.heima.behavior.dto.BehaviorDto;
import com.heima.common.dto.ResponseResult;
import com.heima.common.enums.AppHttpCodeEnum;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.ResourceBundle;

/**
 * @author Mr_Su
 * @version v1.0
 * @date 2022/7/7 11:47
 * @desciption
 */
@Component
@Aspect
public class BehaviorAdvice {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Around("execution(* com.heima.behavior.service.impl.*.*(..))")
    public Object saveBehaviorToRedis(ProceedingJoinPoint pjp){
        /**
         * 举例:
         *      当前登录人关注了某个文章作者 redis中的key: "follow_" + 当前登录人的id + "_" + 当前设备id + "_"+ 某个文章作者id + "_" + 某个文章的id
         *      当前登录人点赞了某个文章 redis中的key: "like" + 当前登录人的id + "_" + 当前设备id + "_"+ 某个文章作者id + "_" + 某个文章的id
         */
        MethodSignature signature = (MethodSignature)pjp.getSignature();
        Method method = signature.getMethod();
        String methodName = method.getName();
        // 判断方法是否以save开头
        if (methodName.startsWith("save")){
            Object[] args = pjp.getArgs();
            BehaviorDto dto = (BehaviorDto) args[0];

            if (dto.getOperation() == 0){
                redisTemplate.boundValueOps(methodName + "_" + dto.getUserId() + "_" + dto.getEquipmentId() + "_"+ dto.getAuthorId() + "_" + dto.getArticleId()).set("");
            }else {
                redisTemplate.delete(methodName + "_" + dto.getUserId() + "_" + dto.getEquipmentId() + "_"+ dto.getAuthorId() + "_" + dto.getArticleId());
            }
        }
        try {
            return pjp.proceed();
        }catch (Throwable throwable){
            throwable.printStackTrace();
        }
        return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR);
    }
}
